package com.example.student.controller;

import com.example.student.model.LoginRequest;
import com.example.student.model.LoginResponse;
import com.example.student.model.RefreshTokenRequest;
import com.example.student.service.AuthService;
import com.example.student.entity.SysUser;
import com.example.student.mapper.SysUserMapper;
import com.example.student.common.Result;
import com.example.student.service.TokenService;
import com.example.student.service.impl.JwtTokenServiceImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Resource
    private AuthService authService;
    
    @Resource
    private SysUserMapper userMapper;
    
    @Resource
    private PasswordEncoder passwordEncoder;
    
    @Resource
    private JwtTokenServiceImpl tokenService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        return Result.success(authService.login(loginRequest, request));
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        String token = tokenService.getTokenFromRequest(request);
        if (token != null && !token.isEmpty()) {
            // 获取当前认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.getPrincipal() instanceof SysUser) {
                SysUser user = (SysUser) authentication.getPrincipal();
                // 将token加入黑名单并从Redis中删除
                tokenService.addToBlacklist(token, user.getId());
                // 清除安全上下文
                SecurityContextHolder.clearContext();
                return Result.success("登出成功");
            }
        }
        return Result.success("登出成功");
    }
    
    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    public Result<Map<String, String>> refreshToken(@Valid @RequestBody RefreshTokenRequest refreshRequest) {
        // 验证refreshToken并生成新的accessToken
        String newAccessToken = tokenService.refreshToken(refreshRequest.getRefreshToken());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("accessToken", newAccessToken);
        return Result.success(tokenMap);
    }
    
    /**
     * 检查token状态
     */
    @GetMapping("/check")
    public Result<Map<String, Object>> checkToken(HttpServletRequest request) {
        String token = tokenService.getTokenFromRequest(request);
        Map<String, Object> result = new HashMap<>();
        result.put("valid", tokenService.validateToken(token));
        return Result.success(result);
    }
    
    /**
     * 重置管理员密码（仅用于开发和紧急情况）
     */
    @PostMapping("/reset-admin-password")
    public ResponseEntity<String> resetAdminPassword(@RequestParam() String username) {
        // 查找admin用户
        SysUser adminUser = userMapper.selectOne(
            new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username)
        );

        if (adminUser == null) {
            return ResponseEntity.badRequest().body(username+"用户不存在");
        }

        // 重置密码为admin123
        String newPassword = username+"123";
        adminUser.setPassword(passwordEncoder.encode(newPassword));

        // 更新用户信息
        userMapper.updateById(adminUser);

        return ResponseEntity.ok("Admin密码已重置为: " + newPassword);
    }
} 